package com.ecarx.library_base.usb;

import android.content.Context;
import android.os.StatFs;
import android.os.storage.StorageManager;

import com.ecarx.library_base.BaseApplication;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;


public class UDiskUtil {


    /**
     * 获取U盘列表
     */
    public static List<UDiskDevice> getUDiskDeviceList() {
        StorageManager storageManager = (StorageManager) BaseApplication.getInstance().getSystemService(Context.STORAGE_SERVICE);
        List<UDiskDevice> uDiskDeviceList = new ArrayList<>();
        try {
            Class storeManagerClazz = Class.forName("android.os.storage.StorageManager");

            Method getVolumesMethod = storeManagerClazz.getMethod("getVolumes");

            List<?> volumeInfos = (List<?>) getVolumesMethod.invoke(storageManager);

            Class volumeInfoClazz = Class.forName("android.os.storage.VolumeInfo");

//            Method getTypeMethod = volumeInfoClazz.getMethod("getType");
            Method getFsUuidMethod = volumeInfoClazz.getMethod("getFsUuid");

//            Field fsTypeField = volumeInfoClazz.getDeclaredField("fsType");
            Field fsLabelField = volumeInfoClazz.getDeclaredField("fsLabel");
            Field pathField = volumeInfoClazz.getDeclaredField("path");
            Field internalPath = volumeInfoClazz.getDeclaredField("internalPath");

            if (volumeInfos == null) {
                return uDiskDeviceList;
            }
            for (Object volumeInfo : volumeInfos) {
                String uuid = (String) getFsUuidMethod.invoke(volumeInfo);
                if (uuid == null) {
                    continue;
                }
//                        String fsTypeString = (String)fsTypeField.get(volumeInfo);
                String fsLabelString = (String) fsLabelField.get(volumeInfo);
                String pathString = (String) pathField.get(volumeInfo);
                String internalPathString = (String) internalPath.get(volumeInfo);
                StatFs statFs = new StatFs(internalPathString);
                long avaibleSize = statFs.getAvailableBytes();
                long totalSize = statFs.getTotalBytes();
                uDiskDeviceList.add(new UDiskDevice(fsLabelString, pathString, internalPathString, statFs, avaibleSize, totalSize, uuid));
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return uDiskDeviceList;
    }
}
